﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace SMS.Common.Silverlight
{
    /// <summary>
    /// Find controls in Silverlight visual tree.
    /// </summary>
    public static class ControlFinder
    {
        /// <summary>
        /// Get children for parent of type 'UIElement'.
        /// </summary>
        /// <typeparam name="T">UIElement</typeparam>
        /// <param name="parent">find children of this parent</param>
        /// <returns>list(s) of children</returns>
        public static List<T> GetChildren<T>(UIElement parent) where T : UIElement
        {
            List<T> list = new List<T>();
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                UIElement child = VisualTreeHelper.GetChild(parent, i) as UIElement;
                if (child != null)
                {
                    if (child is T)
                        list.Add(child as T);

                    List<T> l1 = ControlFinder.GetChildren<T>(child);
                    foreach (T u in l1)
                        list.Add(u);
                }
            }
            return list;
        }
    }
    
    ///// <summary>
    ///// http://geekswithblogs.net/codingbloke/archive/2010/12/19/visual-tree-enumeration.aspx
    ///// </summary>
    //public static class VisualTreeEnumeration
    //{
    //    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)
    //    {
    //        int count = VisualTreeHelper.GetChildrenCount(root);
    //        for (int i = 0; i < count; i++)
    //        {
    //            var child = VisualTreeHelper.GetChild(root, i);
    //            yield return child;
    //            if (depth > 0)
    //            {
    //                foreach (var descendent in Descendents(child, --depth))
    //                    yield return descendent;
    //            }
    //        }
    //    }

    //    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
    //    {
    //        return Descendents(root, Int32.MaxValue);
    //    }

    //    public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
    //    {
    //        DependencyObject current = VisualTreeHelper.GetParent(root);
    //        while (current != null)
    //        {
    //            yield return current;
    //            current = VisualTreeHelper.GetParent(current);
    //        }
    //    }
    //}
}